﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Runtime.Serialization;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Globalization;
using System.Data.Metadata.Edm;

namespace CustomerService
{
    //public partial class SalesManagerEntities : DbContext
    //{
    //    private codeState[] _cachedStates = null;
    //    private codeCountry[] _cachedCountries = null;
    //    private codeLanguage[] _cachedLanguages = null;

    //    public codeState[] CachedStates
    //    {
    //        get
    //        {
    //            if (_cachedStates == null)
    //                _cachedStates = (from c in codeState
    //                                 select c).ToArray();
    //            return _cachedStates;
    //        }
    //    }

    //    public codeCountry[] CachedCountries
    //    {
    //        get
    //        {
    //            if (_cachedCountries == null)
    //                _cachedCountries = (from c in codeCountry
    //                                 select c).ToArray();
    //            return _cachedCountries;
    //        }
    //    }

    //    public codeLanguage[] CachedLanguages
    //    {
    //        get
    //        {
    //            if (_cachedLanguages == null)
    //                _cachedLanguages = (from c in codeLanguage
    //                                    select c).ToArray();
    //            return _cachedLanguages;
    //        }
    //    }
    //}

    public partial class SalesManagerEntities
    {
        public static SalesManagerEntities DefaultContext;
        public static tblSalesManagerUser[] SalesManagerUsers = null;
        internal static int _identityKey = -1;

        public string Decrypt(byte[] value)
        {
            try
            {
                return Database.SqlQuery<string>("select dbo.Decrypt(@value)", new SqlParameter("value", value)).FirstOrDefault();
            }
            catch (Exception)
            {
                return "ERROR";
            }
            //var query = ((IObjectContextAdapter)this).ObjectContext.CreateQuery<string>("select value SalesManagerModel.Store.Decrypt(@value) from {1}");
            //query.Parameters.Add(new System.Data.Objects.ObjectParameter("value", value));
            //var result = query.Execute(System.Data.Objects.MergeOption.NoTracking);
            //return result.FirstOrDefault();
        }

        public byte[] Encrypt(string value)
        {
            return Database.SqlQuery<byte[]>("select dbo.Encrypt(@value)", new SqlParameter("value", value)).FirstOrDefault();
            //var query = ((IObjectContextAdapter)this).ObjectContext.CreateQuery<byte[]>("select value SalesManagerModel.Store.Encrypt(@value) from {1}");
            //query.Parameters.Add(new System.Data.Objects.ObjectParameter("value", value));
            //var result = query.Execute(System.Data.Objects.MergeOption.NoTracking);
            //return result.FirstOrDefault();
        }

        public int Checksum(string value)
        {
            return Database.SqlQuery<int>("select checksum(@value)", new SqlParameter("value", value)).FirstOrDefault();
        }

        public int UserID()
        {
            return Database.SqlQuery<Int32>("select UserID from master..tblSalesManagerUser where [system_user] = system_user").FirstOrDefault();
        }

        public void SaveAllChanges(int customerID)
        {
            tblCustomer customer = tblCustomer.Find(new object[] { customerID });
            tblOrderHeader[] changedOrders = customer.OrderHeaders.Where(c => "PEO".Contains(c.OrderStatusCode)).ToArray();

            if (SaveChanges() > 0)
            {
                spBuildSearchKeys(customerID);
                foreach (tblOrderHeader order in changedOrders)
                {
                    spCalcOrderTotals(order.OrderID);
                    Entry<tblOrderHeader>(order).Reload();
                }
            }
        }

        public static string UserName(int? UserID)
        {
            if (SalesManagerUsers != null && UserID != null)
            {
                tblSalesManagerUser user = SalesManagerUsers.Where(c => c.UserID == (int)UserID).FirstOrDefault();
                if (user != null)
                    return user.system_user;
            }
            return string.Empty;
        }
    }

    public partial class tblPerson 
    {
        partial void Initialize()
        {
            PersonID = SalesManagerEntities._identityKey--;
            FirstName = string.Empty;
            LastName = string.Empty;
            LanguageID = 1;
            //LanguageReference = new System.Data.Objects.DataClasses.EntityReference<codeLanguage>() { EntityKey = new System.Data.EntityKey("SalesManagerEntities.codeLanguage", "LanguageID", 1) };
        }
    }

    public partial class tblAddress 
    {
        partial void Initialize()
        {
            AddressID = SalesManagerEntities._identityKey--;
            Address1 = string.Empty;
            CountryID = 1;
            //CountryReference = new System.Data.Objects.DataClasses.EntityReference<codeCountry>() { EntityKey = new System.Data.EntityKey("SalesManagerEntities.codeCountry", "CountryID", 468) };
        }
    }

    public partial class tblCustomer 
    {
        //public tblOrderHeader[] cachedOrderHeaders;
        //public tblOrderDetail[] cachedOrderDetails;
        //public tblContactPoint[] cachedContactPoints;
        //public tblSequenceOrder[] cachedSequenceOrders;
        //public tblSequenceOrderStep[] cachedSequenceOrderSteps;
        //public tblRefund[] cachedRefunds;
        //public tblRMAReturn[] cachedRMAReturns;
        //public tblReturnDetail[] cachedReturnDetails;
        //public tblTransaction[] cachedTransactions;
        //public tblMiscDef[] cachedMiscDefs;

        partial void Initialize()
        {
            CustomerID = SalesManagerEntities._identityKey--;
            ImportDate = DateTime.Now;
            AllowCleaning = true;
            AllowEmail = true;
            AllowMail = true;
            AllowPhone = true;
            AllowRent = true;
            DoNotProcess = false;
        }
    }

    public partial class tblOrderHeader 
    {
        partial void Initialize()
        {
            OrderID = SalesManagerEntities._identityKey--;
            OrderDate = DateTime.Today;
            ProjShipDate = DateTime.Today;
            ImportDate = DateTime.Today;
            ProductTotal = 0;
            Shipping = 0;
            Taxes = 0;
            OrderTotal = 0;
        }

        public string OrderListInfo
        {
            get
            {
                string ret =
                    OrderDate.ToShortDateString() + "<br />" +
                    OrderStatus.Name;
                // Put the first shipment date into the list info
                //if (OrderStatus.OrderStatusCode == "S" || OrderStatus.OrderStatusCode == "R")
                //    ret += "<br />" + ((DateTime)OrderShipments.OrderBy(o => o.Shipment.ShippedDate).First().Shipment.ShippedDate).ToShortDateString();

                return ret;
            }
        }

        public DateTime RecentShippedDate
        {
            get
            {
                DateTime dt = DateTime.MinValue;
                foreach (tblInventoryTransaction it in this.InventoryTransactions)
                    if (it.Package != null && it.Package.ShippedDate != null && it.Package.ShippedDate > dt)
                        dt = (DateTime)it.Package.ShippedDate;
                if (dt == DateTime.MinValue)
                    dt = ProjShipDate;
                return dt;
            }
        }

        public bool CanEdit
        {
            get { return (OrderStatusCode == "P" || OrderStatusCode == "H"); }
        }

        public bool CanCancel
        {
            get { return (OrderStatusCode == "P" || OrderStatusCode == "H" || OrderStatusCode == "E"); }
        }

        public bool CanRefund
        {
            get { return true; }
        }

        public string Agent
        {
            get { return SalesManagerEntities.UserName(AgentID); }
        }
    }

    public partial class tblOrderDetail 
    {
        partial void Initialize()
        {
            OrderDetailID = SalesManagerEntities._identityKey--;
        }

        public decimal TotalPrice
        {
            get { return Convert.ToDecimal(Qty * (Convert.ToDouble(UnitPrice) * (1 - Discount))); }
        }

        public string DisplayDiscount
        {
            get
            {
                return ((decimal)UnitPrice * (decimal)(double)Discount).ToString("C");
            }
            set
            {
                decimal d = 0;

                if (decimal.TryParse(value, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out d))
                {
                    if (UnitPrice == 0)
                        Discount = 0;
                    else
                        Discount = (double)(d / (decimal)UnitPrice);
                }
            }
        }
    }

    public partial class tblRefund 
    {
        partial void Initialize()
        {
            RefundID = SalesManagerEntities._identityKey--;
        }

        public string LineDescription
        {
            get
            {
                if (OrderDetailID != null)
                    return OrderDetail.Product.ShortName;
                if (OrderTaxID != null)
                    return OrderTax.TaxRate.Name;
                return "Shipping";
            }
        }

        public bool CanDelete
        {
            get
            {
                return (this.Transaction == null) ||
                    (this.Transaction.TransactionStatusCode != "P" && this.Transaction.TransactionStatusCode != "I");
            }
        }
    }

    public partial class tblTransaction
    {
        partial void Initialize()
        {
            TransactionID = SalesManagerEntities._identityKey--;
        }
    }

    public partial class tblTransactionSubmit
    {
        partial void Initialize()
        {
        }

        public string TransactionSubmitType
        {
            get
            {
                switch (TransactionSubmitTypeCode)
                {
                    case "A": return "Authorization";
                    case "D": return "Deposit";
                    default: return string.Empty;
                }
            }
        }

        public string Decision1
        {
            get
            {
                switch (Decision)
                {
                    case "A": return "Accepted";
                    case "D": return "Declined";
                    case "E": return "Errored";
                    case "H": return "Held for review";
                    default: return string.Empty;
                }
            }
        }
    }

    public partial class tblAccount 
    {
        private string _savedAccountNumber = null;

        public tblAccount(tblOrderHeader oh) : this()
        {
            OwnerID = oh.OwnerID;
            Person = oh.Customer.Person;
            Address = oh.Customer.Person.Address;
            oh.tblAccount = this;
        }

        public tblAccount(tblSequenceOrder so)
            : this()
        {
            OwnerID = so.OwnerID;
            Person = so.Customer.Person;
            Address = so.Customer.Person.Address;
            so.Account = this;
        }

        partial void Initialize()
        {
            AccountID = SalesManagerEntities._identityKey--;
            CreateDate = DateTime.Now;
            CurrencyID = 1; 
        }

        public string GetAccountNumber(SalesManagerEntities context)
        {
            if (_savedAccountNumber == null)
                _savedAccountNumber = context.Decrypt(AccountNumber);
            if (_savedAccountNumber != null)
                _savedAccountNumber = _savedAccountNumber.Trim();
            return _savedAccountNumber;
        }

        public void SetAccountNumber(SalesManagerEntities context, string value)
        {
            _savedAccountNumber = value;
            AccountNumber = context.Encrypt(value);
            Checksum = context.Checksum(value);
        }

        public string CardNumber1
        {
            get { return string.Empty; }
        }
    }

    public partial class tblProduct
    {
        public decimal DefaultPrice
        {
            get
            {
                tblProductPricing pp = ProductPricing.Where(c => c.ProductPricingClassCode == 1).FirstOrDefault();
                return (pp == null) ? 0 : pp.Price;
            }
        }
    }

    public partial class tblNote
    {
        partial void Initialize()
        {
            NoteID = SalesManagerEntities._identityKey--;
            NoteDate = DateTime.Now;
        }

        public string Agent
        {
            get { return SalesManagerEntities.UserName(AgentID); }
        }
    }

    public partial class tblOrderNote
    {
        partial void Initialize()
        {
            OrderNoteID = SalesManagerEntities._identityKey--;
        }
    }

    public partial class tblCustomerNote
    {
        partial void Initialize()
        {
            CustomerNoteID = SalesManagerEntities._identityKey--;
        }
    }

    public partial class tblSalesManagerUser
    {
        public int UserID { get; set; }
        public string system_user { get; set; }
    }

    public partial class tblSequenceOrder
    {
        partial void Initialize()
        {
            SequenceOrderID = SalesManagerEntities._identityKey--;
        }

        public bool CanEdit
        {
            get { return SequenceStatusCode == "A"; }
        }
    }

    public partial class tblSequenceOrderStep
    {
        partial void Initialize()
        {
            SequenceOrderStepID = SalesManagerEntities._identityKey--;
        }
    }

    public partial class tblSequenceOrderStepProduct
    {
        partial void Initialize()
        {
            SequenceOrderStepProductID = SalesManagerEntities._identityKey--;
        }
        
        public string DisplayDiscount
        {
            get
            {
                return (Discount == null || UnitPrice == null) ? "0" : ((decimal)UnitPrice * (decimal)(double)Discount).ToString("C");
            }
            set
            {
                decimal d = 0;

                if (decimal.TryParse(value, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out d))
                {
                    if ((d != 0 || Discount != null ) && UnitPrice != null && UnitPrice != 0)
                        Discount = (double)(d / (decimal)UnitPrice);
                }
            }
        }
    }


}
